package version2;

import net.fortuna.ical4j.data.CalendarOutputter;
import net.fortuna.ical4j.model.*;
import net.fortuna.ical4j.model.component.VAlarm;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.component.VTimeZone;
import net.fortuna.ical4j.model.parameter.Cn;
import net.fortuna.ical4j.model.parameter.Role;
import net.fortuna.ical4j.model.property.*;
import net.fortuna.ical4j.util.UidGenerator;
import org.apache.commons.lang.time.DateUtils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.net.URI;
import java.util.Date;
import java.util.List;

/**
 * Description:
 *
 * @author JourWon
 * @date 2021/4/8 17:04
 */
class outics {
    /**
     * 导出文件
     */
    public static void exportFile(List<List<List<String>>> data , List<Date> dates) {
        try {
            // 创建一个时区（TimeZone）
            TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
            TimeZone timezone = registry.getTimeZone("Asia/Shanghai");
            VTimeZone tz = timezone.getVTimeZone();

            // 创建日历
            Calendar calendar = new Calendar();
            calendar.getProperties().add(new ProdId("-//Ben Fortuna//iCal4j 1.0//EN"));
            calendar.getProperties().add(Version.VERSION_2_0);
            calendar.getProperties().add(CalScale.GREGORIAN);

            //数据匹配
            for (int i=1;i<7; i++){     //行
                List<List<String>> row = data.get(i);
                for (int j=1;j<8; j++){       //单元格
                    List<String> cell = row.get(j);
                    if (!cell.get(0).equals("")) {
                        Dateof dateof = new Dateof(cell);
                        List<String> da = dateof.summary();
                        for (int number=1; number<=(da.size()/4);number++){

                            //时间基值
                            Date star1 = dates.get(i*2-2);
                            Date end1 = dates.get(i*2-1);

                            // 时间主题
                            String summary = da.get(number*4-4);

                            // 开始时间
                            int begin = da.get(number*4-3).indexOf("-");
                            if (begin == -1) begin = da.get(number*4-3).length();
                            int toDay = Integer.parseInt( da.get(number*4-3).substring(0,begin));

                            // 开始时间偏移量
                            star1 = DateUtils.addDays(star1,(toDay-1)*7+(j-1));
                            DateTime start2 = new DateTime(star1);

                            // 开始时间转换为UTC时间（UTC ＋ 时区差 ＝ 本地时间 ）
                            start2.setUtc(true);

                            // 结束时间偏移值
                            end1 = DateUtils.addDays(end1,(toDay-1)*7+(j-1));
                            if (da.get(number*4-2).length()==1){
                                end1 = DateUtils.addMinutes(star1,45);  //设置只有一节课的结束时间
                            }
                            DateTime end2 = new DateTime(end1);

                            // 结束时间设置成UTC时间（UTC ＋ 时区差 ＝ 本地时间 ）
                            end2.setUtc(true);

                            // 新建普通事件
                            VEvent event = new VEvent(start2, end2, summary);

                            //事件概述（教室+老师）
                            event.getProperties().add(new Location(da.get(number*4-1)));

                            // 生成唯一标示
                            event.getProperties().add(new Uid(new UidGenerator("iCal4j").generateUid().getValue()));

                            // 添加时区信息
                            event.getProperties().add(tz.getTimeZoneId());

                            // 添加邀请者
                            Attendee dev1 = new Attendee(URI.create("mailto:haifongzhong288@gmail.com"));
                            dev1.getParameters().add(Role.REQ_PARTICIPANT);
                            dev1.getParameters().add(new Cn("Student"));
                            event.getProperties().add(dev1);

                            // 重复事件
                            int len = da.get(number*4-3).indexOf(" ");
                            int finish;
                            boolean isInterval = true;
                            if (len == -1) {
                                if (begin == da.get(number*4-3).length()) finish = 0;
                                else {
                                    finish = Integer.parseInt(da.get(number *4-3).substring(begin + 1));
                                    finish -= toDay;
                                }
                                isInterval = false;
                            }else {
                                finish = Integer.parseInt(da.get(number * 4 - 3).substring(begin + 1, len));
                                finish -= (toDay);
                                finish /=2;
                            }
                            Recur recur = new Recur(Recur.WEEKLY,++finish);
                            if(isInterval) recur.setInterval(2);

                            RRule rule = new RRule(recur);
                            event.getProperties().add(rule);

                            // 提醒,提前20分钟
                            VAlarm valarm = new VAlarm(new Dur(0, 0, -20, 0));
                            valarm.getProperties().add(new Summary("Event Alarm"));
                            valarm.getProperties().add(Action.DISPLAY);
                            valarm.getProperties().add(new Description("Progress Meeting at 9:30am"));

                            // 将VAlarm加入VEvent
                            event.getAlarms().add(valarm);

                            // 添加事件
                            calendar.getComponents().add(event);

                            // 验证
                            calendar.validate();

                            //数据输出为ics文件
                            FileOutputStream fout = new FileOutputStream("C:\\Users\\haifongzhong\\IdeaProjects\\学生课表.ics");
                            CalendarOutputter outputter = new CalendarOutputter();
                            outputter.output(calendar, fout);
                        }
                    }
                }
            }

        } catch (SocketException | ValidationException | FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
